/*
 * @Author: lizhil
 * @Date: 2021-12-31 11:03:04
 * @Last Modified by: lizhil
 * @Last Modified time: 2022-11-03 22:29:21
 */
const axios = require('axios')
const crypto = require('crypto')
const moment = require('moment')
const boxen = require('boxen')

const sign = (arr) => {
  const encrypt = arr
  const md5Str = encrypt.join('')

  return md5(md5Str)
}

module.exports = (options) => {
  const { baseURL, appKey, appSecret, debug } = options

  const instance = axios.create({
    baseURL,
    headers: {},
    debug,
    logs: [],
    _boxen(log, type = 'log') {
      if (Array.isArray(log)) log = log.join('\n')

      console[type](boxen(log, { padding: 1 }))
    },
    onSuccess(res) {
      this.logs.push(`[Success] ${res.msg}`)
      this._boxen(this.logs)
      return Promise.resolve(res)
    },
    onFail(error, res) {
      this.logs.push(`[Error] ${error}`)
      this._boxen(this.logs, 'error')
      return Promise.reject([error, res])
    },
  })

  instance.interceptors.request.use(
    (config) => {
      const method = config.method.toLocaleUpperCase()

      if (config.debug) {
        config.logs.push(`[${method}] ${config.baseURL}${config.url}`)
        if (method == 'GET') {
          config.logs.push(`[Data] ` + JSON.stringify(config.params))
        } else {
          config.logs.push(`[Data] ` + JSON.stringify(config.data))
        }
      }

      return config
    },
    (error) => {
      return Promise.reject([error])
    }
  )

  instance.interceptors.response.use(
    async (response) => {
      const { config, status } = response

      if (status == 200) {
        const data = response.data

        if (data.code == 200) {
          return config.onSuccess(data)
        } else {
          return config.onFail(data.msg, data)
        }
      } else {
        throw '服务器异常'
      }
    },
    (error) => {
      const { config, response } = error

      if (response) {
        return config.onFail('服务器异常', response.data)
      } else {
        if (config) {
          return config.onFail(error.message, error)
        } else {
          return Promise.reject([error])
        }
      }
    }
  )

  return instance
}
